package com.chapp.lastFmWs;

import java.io.IOException;
import java.net.URLEncoder;

import android.content.Context;
import android.util.Log;

import com.chapp.R;
import com.google.resting.Resting;
import com.google.resting.component.RequestParams;
import com.google.resting.component.impl.BasicRequestParams;

final public class RestClientLastFm {

	private String url;
	private String apiKey;
	private Context context;
	// private final String tag = "restclient";
	private RequestParams params;

	private final String LIMIT_SEARCH = "10";

	public RestClientLastFm(Context context) {
		this.context = context;
		this.url = this.context.getString(R.string.url);
		this.apiKey = this.context.getString(R.string.api_key);
	}

	private void initSearch(String method, int page) {
		params = new BasicRequestParams();
		params.add("limit", LIMIT_SEARCH);
		params.add("page", String.valueOf(page));
		params.add("method", method);
	}

	private String callService(RequestParams params) throws IOException {
		params.add("api_key", this.apiKey);

		String xmlResponse = null;
		try {
			xmlResponse = Resting.get(this.url, 80, params).getResponseString();
		} catch (Exception e) {
			throw new IOException(e.getLocalizedMessage());
		}
		return xmlResponse;
	}

	public String searchArtist(String artist, int page) throws IOException {
		initSearch("artist.search", page);
		params.add("artist", URLEncoder.encode(artist));
		return this.callService(params);
	}

	public String searchVenue(String venue, int page) throws IOException {
		initSearch("venue.search", page);
		params.add("venue", URLEncoder.encode(venue));
		return this.callService(params);
	}

	public String searchLocationEvents(String location, int page)
			throws IOException {
		initSearch("geo.getevents", page);
		params.add("location", location);
		return this.callService(params);
	}

	public String searchVenueEvents(String location, int page)
			throws IOException {
		initSearch("venue.getevents", page);
		params.add("venue", location);
		return this.callService(params);
	}

	public String searchLocationEvents(double latitud, double longitud,
			int distance, int page) throws IOException {
		initSearch("geo.getevents", page);
		params.add("lat", String.valueOf(latitud));
		params.add("long", String.valueOf(longitud));
		Log.e("ddfghjk}2", "---> " + distance);
		params.add("distance", String.valueOf(distance));
		return this.callService(params);
	}

	public String searchArtistEvents(String name, int page) throws IOException {
		initSearch("artist.getEvents", page);
		params.add("artist", name);
		params.add("autocorrect", "1");
		return this.callService(params);
	}

}
